package liuyang.bigeventserver.modules.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import liuyang.bigeventserver.common.CacheService;
import liuyang.bigeventserver.common.R;
import liuyang.bigeventserver.modules.security.jwt.JwtTokenExtractor;
import liuyang.bigeventserver.modules.security.jwt.JwtTokenService;
import liuyang.bigeventserver.modules.security.jwt.vo.PrincipalInfo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author xconf
 * @since 2024/2/28
 */
@Component
@Slf4j
@AllArgsConstructor
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {

    private final ObjectMapper om;
    private final JwtTokenService jwtTokenService;
    private final CacheService cacheService;// 计划后续用这个替代直接使用redisTemplate
    private final RedisTemplate<String, Object> redisTemplate3;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //ObjectMapper om = new ObjectMapper();

        // For Session
        /*if (authentication != null && authentication.getDetails() != null) {
            request.getSession().invalidate();
        }*/

        // For JWT
        // 删掉redis中的jwt token
        final String token = JwtTokenExtractor.extract(request);
        if (StringUtils.isNotEmpty(token) && StringUtils.isNotBlank(token)) {
            final PrincipalInfo info = jwtTokenService.verify(token);
            // 删除Redis缓存中信息
            log.debug("username = {}", info.getSubject());
            redisTemplate3.delete(info.getSubject());
        }

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println(om.writeValueAsString(R.ok("注销成功")));

        log.debug("注销成功");
    }
}